package com.changgou.system.util;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * JWT工具类
 */
public class JwtUtil {

    //设置jwt令牌有效期
    public static final long JWT_TTL = 3600000L;

    //设置密钥明文
    public static final String JWT_KEY = "itcast";

    /**
     * 创建token
     */
    public static String createJWT(String id, String subject, Long ttlMills){

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //如果输入过期时间为空，则指定默认过期时间
        if (ttlMills == null) {
            ttlMills = nowMillis;
        }

        //令牌过期的时间点为现在的时间加设置后的过期时间
        long expMills = ttlMills + nowMillis;
        Date expDate = new Date(expMills);

        //生成加密后的密钥
        SecretKey secretKey = generalKey();

        //生成jwt令牌
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .setIssuer("admin")
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .setExpiration(expDate);

        //编码
        return jwtBuilder.compact();
    }

    //生成加密后的密钥
    private static SecretKey generalKey() {

        byte[] decode = Base64.getDecoder().decode(JWT_KEY);
        SecretKey secretKey = new SecretKeySpec(decode,0,decode.length,"AES");
        return secretKey;
    }

}
